package com.itheima.reggie.web.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.config.common.BaseContext;
import com.itheima.reggie.config.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址簿管理
 *
 * @Name AddressBookController
 * @Author BaiXin
 * @Date 2022-11-06 9:55
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        // 从当前线程绑定对象中获取用户id
        Long userId = BaseContext.getThreadLocal();

        log.info("查询所有收货地址", userId);


        LambdaQueryWrapper<AddressBook> querywrapper = new LambdaQueryWrapper<>();
        // 设置查询条件：用户id

        Wrapper<AddressBook> qw = Wrappers.lambdaQuery(AddressBook.class)
                .eq(AddressBook::getUserId, userId)
                .orderByDesc(AddressBook::getIsDefault)
                .orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> addressBooks = addressBookService.list(qw);

        return R.success(addressBooks);

    }

    /**
     * 新增收货地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    public R save(@RequestBody AddressBook addressBook) {

        // 获取当前登录用户id
        Long userId = BaseContext.getThreadLocal();
        addressBook.setUserId(userId);
        addressBookService.save(addressBook);
        return R.success("添加地址成功");

    }

    /**
     * 根据id查询
     *
     * @param id 要查询的id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id查询：{}", id);


        if (id != null) {

            AddressBook addressBook = addressBookService.getById(id);
            return R.success(addressBook);
        }

        return R.error("参数有误");
    }

    /**
     * 修改地址
     * 1. 检查地址中userId是否为空，为空则不允许修改
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook) {
        log.info("修改地址信息：{}", addressBook.toString());

        addressBookService.updateById(addressBook);
        return R.success("修改成功");

    }

    /**
     * 设置默认收货地址
     *
     * @param addressBook 默认的收货地址id
     * @return
     */
    @PutMapping("/default")
    public R setDefaultAddress(@RequestBody AddressBook addressBook) {
        log.info("设置默认收货地址：{}", addressBook.getId());
        // 提交修改
        addressBookService.setDefaultAddress(addressBook);
        return R.success("默认地址设置成功");
    }


    /**
     * 按照id删除，支持批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R removeByIds(@RequestParam("ids") List<Long> ids) {
        addressBookService.removeByIds(ids);
        return R.success("删除成功");

    }

    /**
     * 查询默认地址。
     * 隐含条件：
     * 1. 当前登录用户id
     * 2. 地址为默认地址，is_default=1
     */
    @GetMapping("default")
    public R<AddressBook> getDefault() {

        // 获取用户id
        Long userId = BaseContext.getThreadLocal();

        log.info("查询当前登录用户【{}】的默认收货地址", userId);

        // 构造条件对象，封装查询条件
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        return R.success(addressBook);


    }
}
